package com.blockmeta.bbs.immodule.fragment;


import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.base.adapter.BaseTabViewPagerAdapter;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.widget.ToggleScrollViewPager;
import com.blockmeta.bbs.baselibrary.widget.tab.SlidingTabLayout;
import com.blockmeta.bbs.businesslibrary.activity.CustomQrCodeActivity;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseLazyFragment;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.eventbus.XGPushEvent;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.DeepLinkUtils;
import com.blockmeta.bbs.businesslibrary.util.DialogUtil;
import com.blockmeta.bbs.businesslibrary.util.RouterActivityHelper;
import com.blockmeta.bbs.immodule.R;
import com.blockmeta.bbs.immodule.R2;
import com.blockmeta.bbs.immodule.activity.IMSearchNormalResultActivity;
import com.blockmeta.bbs.immodule.activity.RecommandUserActivity;
import com.blockmeta.bbs.immodule.widget.IMGoLoginMsg;
import com.hellobike.flutter.thrio.navigator.ThrioNavigator;
import com.king.zxing.Intents;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 */
@Route(path = RouterPath.IM_HOME_FRAGMENT)
public class IMHomeFragment extends BaseLazyFragment implements View.OnClickListener {
    @BindView(R2.id.simple_search)
    LinearLayout mSimpleSearch;
    @BindView(R2.id.ll_back)
    LinearLayout mLLBack;

    @BindView(R2.id.simple_add)
    LinearLayout mSimpleAdd;
    @BindView(R2.id.simple_title)
    ConstraintLayout mSimpleTitle;
    @BindView(R2.id.vp_container)
    ToggleScrollViewPager mViewPager;
    @BindView(R2.id.header_tab)
    SlidingTabLayout mTabLayout;


    private PopupWindow mPopupWindow;

    public IMHomeFragment() {
        // Required empty public constructor
    }

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        EventBus.getDefault().register(this);
        return inflater.inflate(R.layout.fragment_imhome, container, false);
    }

    @Override
    protected void initializeLayout() {
        mViewPager.setCanScroll(false);
        List<Fragment> fragments = new ArrayList<>(4);
        Fragment session = new IMSessionListFragment();
        Fragment address = new AddressBookFragment();
        fragments.add(session);
        fragments.add(address);
        List<String> title = new ArrayList<>(4);
        title.add("聊天中");
        title.add("通讯录");
        BaseTabViewPagerAdapter vpAdapter = new BaseTabViewPagerAdapter(getChildFragmentManager(), fragments, title);
        mViewPager.setAdapter(vpAdapter);

        mTabLayout.setViewPager(mViewPager);
    }

    @Override
    protected void netWork() {

    }

    @OnClick({R2.id.simple_search, R2.id.simple_add, R2.id.ll_back})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.simple_search) {
            //搜索人或圈子
            startActivity(new Intent(mContext, IMSearchNormalResultActivity.class));
        }else if (i == R.id.simple_add) {
            //添加好友,加入圈子，扫一扫
            showPopMenu();
        }else if(i == R.id.ll_back){
            getActivity().finish();
        }
    }

    private void showPopMenu() {
        if (mPopupWindow == null) {
            View content = LayoutInflater.from(mContext).inflate(R.layout.pop_im_add, null);
            content.findViewById(R.id.ll_join_circle).setOnClickListener(this);
            content.findViewById(R.id.ll_add_friend).setOnClickListener(this);
            content.findViewById(R.id.ll_scan).setOnClickListener(this);
            content.findViewById(R.id.ll_create_circle).setOnClickListener(this);

            mPopupWindow = new PopupWindow(content, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            mPopupWindow.setFocusable(true);
            mPopupWindow.setTouchable(true);
            mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        }
        mPopupWindow.showAsDropDown(mSimpleTitle, 0, 0, Gravity.RIGHT | Gravity.BOTTOM);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.ll_join_circle) {
            //加入圈子
            Log.d("flutterting", "opendeployList");
            ThrioNavigator.push("/activity/deployList",
                    "test",
                    true,
                    (view) -> {
                        return null;
                    }
            );
        } else if (i == R.id.ll_add_friend) {
            //添加好友
            startActivity(new Intent(getActivity(), RecommandUserActivity.class));
        } else if (i == R.id.ll_scan) {
            requestCamera();
        } else if (i == R.id.ll_create_circle) {
            Log.d("flutterting", "openselectpage");
            ThrioNavigator.push("/home/select",
                    "test",
                    true,
                    (view) -> {
                        return null;
                    }
            );
        } else {
        }
        mPopupWindow.dismiss();
    }

    //获取相机权限
    @SuppressLint("CheckResult")
    private void requestCamera() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean granted) throws Exception {
                        if (granted) {
                            LogUtils.i("author" + "start scan qrcode");
                            //扫一扫
                            Intent intent = new Intent(mContext, CustomQrCodeActivity.class);
                            startActivityForResult(intent, Constant.START_QRCODE);
                        } else {
                            DialogUtil.showOpenAppSettingDialog();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        DialogUtil.showOpenAppSettingDialog();
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && data != null){
            switch (requestCode){
                case Constant.START_QRCODE:
                    String url = data.getStringExtra(Intents.Scan.RESULT);
                    analyzeQrCode(mContext, url);
                    break;
            }
        }
    }

    private static void analyzeQrCode(Context context, String url) {
        if (TextUtils.isEmpty(url) || Uri.parse(url) == null) {
            ToastUtil.show("请扫描正确的二维码");
            return;
        }
        if (url.startsWith("http") && (url.contains("mall/item") || url.contains("mall/checkout"))) {
            RouterActivityHelper.openNewWeb(context, url);
        } else {
            String regexUri = DeepLinkUtils.regexUri(url);
            Uri uri = Uri.parse(regexUri);
            DeepLinkUtils.jumpToTarget(context, uri);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void resume() {
        if(isHidden()){
            return;
        }
        if (AccountHelper.isLogin()) {
            mSimpleAdd.setVisibility(View.VISIBLE);
        } else {
            mSimpleAdd.setVisibility(View.INVISIBLE);
            //提示登陆
            IMGoLoginMsg imGoLoginMsg = new IMGoLoginMsg(getActivity());
            imGoLoginMsg.show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void LoginUI(MsgSuccess message) {
        if (message.msg.equals("LOGIN") && AccountHelper.isLogin() && AccountHelper.getUserPhonePOJO() != null) {
            resume();
        }
    }

    @Subscribe(sticky = true)
    public void XGPush(XGPushEvent xgPushEvent) {
        if (xgPushEvent.target == XGPushEvent.IM) {
            mTabLayout.setCurrentTab(xgPushEvent.tabNo);
            EventBus.getDefault().removeStickyEvent(xgPushEvent);
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
